"use strict";

/**
 * 构建一个filter
 */
if (!Array.prototype.filter) {
    Array.prototype.filter = function (fun /* , thisArg*/) {
        "use strict";
        if (this === void 0 || this === null)
            throw new TypeError();

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function")
            throw new TypeError();

        var res = [];
        var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
        for (var i = 0; i < len; i++) {
            if (i in t) {
                var val = t[i];

                // NOTE: Technically this should Object.defineProperty at
                //       the next index, as push can be affected by
                //       properties on Object.prototype and Array.prototype.
                //       But that method's new, and collisions should be
                //       rare, so use the more-compatible alternative.
                if (fun.call(thisArg, val, i, t))
                    res.push(val);
            }
        }
        return res;
    };
}
/**
 * 构建一个findIndex
 */
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
if (!Array.prototype.findIndex) {
    Object.defineProperty(Array.prototype, 'findIndex', {
        value: function (predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }

            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];

            // 5. Let k be 0.
            var k = 0;

            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return k.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return k;
                }
                // e. Increase k by 1.
                k++;
            }

            // 7. Return -1.
            return -1;
        }
    });
}

// $.each(document.scripts, function (i, item) {
//     if (item.src.indexOf('vue-lazyload.js') > -1) {
//         Vue.use(VueLazyload, {
//             preLoad: 1.3,
//             error: 'error.png',
//             loading: 'error.png',
//             attempt: 1
//         })
//         return false
//     }
// })


var XNumber = Vue.extend({
    template: '<div class="weui-cells alone">\n' +
    '  <div class="weui-cell">\n' +
    '    <div class="weui-cell__bd">\n' +
    '      <p>{{ title }}</p>\n' +
    '    </div>\n' +
    '<div class="weui_cell_ft clearfix" v-show="!readonly">\n' +
    '<a @click="sub" class="number-selector number-selector-sub" :class="{\'number-disabled\':disabledMin}">-</a>\n' +
    '<span class="number-input" :style="{width: width+\'px\'}" style="display: inline-block">{{ currentValue }}</span>\n' +
    '<input v-model.number="currentValue" type="hidden" pattern="[0-9]*"/>\n' +
    '<a @click="add" class="number-selector number-selector-plus" :class="{\'number-disabled\':disabledMax}">+</a>\n' +
    '</div>\n' +
    '  </div>\n' +
    '</div>',
    props: {
        min: Number,
        max: Number,
        name: String,
        step: {
            type: Number,
            default: 1
        },
        value: {
            default: 1
        },
        title: String,
        readonly: Boolean,
        fillable: {
            type: Boolean,
            default: true
        },
        width: {
            type: Number,
            default: 50
        }
    },
    data: function () {
        return {
            currentValue: 0
        }
    },
    created: function () {
        this.currentValue = Number(this.value)
    },
    computed: {
        disabledMin: function () {
            return typeof this.min === 'undefined' ? false : this.currentValue <= this.min
        },
        disabledMax: function () {
            return typeof this.max === 'undefined' ? false : this.currentValue >= this.max
        }
    },
    watch: {
        currentValue: function (newValue, old) {
            if (this.min && this.value < this.min) {
                this.currentValue = this.min
            }
            if (this.max && this.value > this.max) {
                this.currentValue = this.max
            }
            this.$emit('input', this.currentValue);
            this.$emit('on-change', this.currentValue)
        },
        value: function (value) {
            this.currentValue = Number(value)
        }
    },
    methods: {
        add: function () {
            if (!this.disabledMax) {
                this.currentValue += this.step
            } else {
                this.$emit('input', this.max);
            }
        },
        sub: function () {
            if (!this.disabledMin) {
                this.currentValue -= this.step
            } else {
                this.$emit('input', this.min);
            }
        }
    }
});
Vue.component('XNumber', XNumber)
// window.onload = function () {
//     var loadings = $('#loading')
//     loadings.fadeOut(500)
// }
/**
 * 抛出接口
 */
var common = {
    checkBrower: function () {
        var u = navigator.userAgent, app = navigator.appVersion;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
            iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, //是否iPad
            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
            weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
            qq: u.match(/\sQQ/i) == " qq" //是否QQ
        };
    },
    // 座位状态颜色标记
    seat_color: {
        remain: '#8c0000', // 可售
        sold: '#bdbebd', // 已售
        lock: '#597992', // 冻结
        booking: '#4eaaa0', // 预留
        ban: '#cfb577', // 禁售
        select: '#0ad6e3' // 选中
    },
    filters: {
        empty: function (str, val) {
            return !str ? val : str
        },
        formatTime: function (time, cFormat) {
            if (arguments.length === 0 || !time) {
                return null
            }

            if ((time + '').length === 10) {
                time = +time * 1000
            }

            var format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}',
                date
            if (typeof time === 'object') {
                date = time
            } else {
                time = time.replace(/\-/g, "/")
                date = new Date(time)
            }
            var formatObj = {
                y: date.getFullYear(),
                m: date.getMonth() + 1,
                d: date.getDate(),
                h: date.getHours(),
                i: date.getMinutes(),
                s: date.getSeconds(),
                a: date.getDay()
            }
            var time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, function (result, key) {
                var value = formatObj[key]
                if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
                if (result.length > 0 && value < 10) {
                    value = '0' + value
                }
                return value || 0
            })
            return time_str
        }
    },
    // html字符转义
    showHTML: function (val) {
        if (!val) return '暂无内容'
        return val
            .replace(val ? /&(?!#?\w+;)/g : /&/g, '&amp;')
            .replace(/&lt;/g, "<")
            .replace(/&gt;/g, ">")
            .replace(/&quot;/g, "\"")
            .replace(/&#39;/g, "\'")
            .replace(/src=/g, "data-src=");
    },
    /**
     * 常用前端页面正则校验
     * */
    checked: {
        //手机号码
        mobile: /^1\d{10}$/,
        //帐号，字母开头，可接数字跟_,6-18长度
        account: /^[a-zA-Z][a-zA-Z0-9_]{5,17}$/,
        //密码长度在6-18
        password: /^\w{6,18}$/,
        //数字
        number: /^[0-9]*$/,
        //价格
        price: /^(([1-9]\d{0,9})|0)(\.\d{1,2})?$/,
        //邮箱
        email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,
        //url
        url: /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/
    },
    is_mobile: function (value) {
        return this.checked.mobile.test(value);
    },
    is_account: function (value) {
        return this.checked.account.test(value);
    },
    is_password: function (value) {
        return this.checked.password.test(value);
    },
    is_number: function (value) {
        return this.checked.number.test(value);
    },
    is_price: function (value) {
        return this.checked.price.test(value);
    },
    is_email: function (value) {
        return this.checked.email.test(value);
    },
    is_url: function (value) {
        return this.checked.url.test(value);
    },
    /**
     * 获取当前时间
     * format： 类型
     */
    nowTime: function (format) {
        format = format || 'Y-m-d'

        //timestamp是整数，否则要parseInt转换,不会出现少个0的情况
        var now = new Date();
        var year = this.complement(now.getFullYear())
        var month = this.complement(now.getMonth() + 1)
        var date = this.complement(now.getDate())
        var hour = this.complement(now.getHours())
        var minute = this.complement(now.getMinutes())
        var second = this.complement(now.getSeconds())
        switch (format) {
            case 'Y-m-d H:i:s':
                return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
            case 'Y/m/d H:i:s':
                return year + "/" + month + "/" + date + " " + hour + ":" + minute + ":" + second
            case 'Y-m-d H:i':
                return year + "-" + month + "-" + date + " " + hour + ":" + minute
            case 'Y-m-d':
                return year + "-" + month + "-" + date
            case 'H:i:s':
                return hour + ":" + minute + ":" + second
            case 'H:i':
                return hour + ":" + minute
            default:
                return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
        }
    },
    /**
     * 计算banner图高度
     * @param width 图片宽度
     * @return {*}
     */
    getImgHeight: function (width) {
        if(!width) return false
        return Number(width) / 1.6
    },
    /**
     * 获取当前控制器路径
     * 参数说明
     * fun_name：方法名
     * level: 项目层级，默认3级
     * */
    getPathName: function (fun_name, level) {
        if (!fun_name) return;
        level = level || 3
        var t_pathname = window.location.pathname,
            n_pathname = '';
        if (fun_name.split('/').length > 1) {
            return fun_name
        }
        t_pathname = t_pathname.substr(1);
        var name = t_pathname.split('/');
        var i = 0;
        if (name[0] == 'index.php') {
            level += 1
        }
        for (i; i < level; i++) {
            n_pathname += '/' + name[i]
        }
        return n_pathname + '/' + fun_name;
    },
    /**
     *  设置AJAX数据请求
     *  @param  {[String]} url      [请求路径]
     *  @param  {[JSON]}   data     [发送参数]
     *  @param  {[Object]} callback [成功后的回调函数]
     *  @param  {[String]} type     [发送请求类型('post','get')]
     *  @param  {[String]} async     [发送请求类型('post','get')]
     *  @return {[JSON]}            [服务器返回json数据]
     */
    ajaxSubmit: function (url, data, callback, type, async) {
        var _this = this
        type = type || 'get';
        if (typeof (callback) != "function") {
            callback = function () {
            }
        }
        async = async || false
        $.ajax({
            url: url,
            async: async,
            type: type,
            data: data,
            // dataType: 'JSON',
            beforeSend: function (XMLHttpRequest) {
                // console.log(XMLHttpRequest)
            },
            complete: function (XMLHttpRequest) {
                // console.log(XMLHttpRequest)
                if (!XMLHttpRequest.responseText.match("^\{(.+:.+,*){1,}\}$")) {
                    console.log(XMLHttpRequest.responseText)
                } else {
                    var data = $.parseJSON(XMLHttpRequest.responseText);
                    //#todo 统一错误处理
                    if (data.code != 200) {
                        $.toast(data.message, 'text')
                        return false
                    }
                }
            },
            success: callback,
            error: function (req) {
                console.log(req)
            }
        });
    },
    /**
     *  设置get请求
     *  @param  {[String]} url      [请求路径]
     *  @param  {[JSON]}   data     [发送参数]
     *  @param  {[Object]} callback [成功后的回调函数]
     *  @param  {[Boolean]} async [是否异步]
     *  @return {[JSON]}            [服务器返回json数据]
     */
    DataGet: function (url, data, callback, async) {
        this.ajaxSubmit(url, data, callback, 'get', async)
    },
    /**
     *  设置post请求
     *  @param  {[String]} url      [请求路径]
     *  @param  {[JSON]}   data     [发送参数]
     *  @param  {[Object]} callback [成功后的回调函数]
     *  @param  {[Boolean]} async [是否异步]
     *  @return {[JSON]}            [服务器返回json数据]
     */
    DataPost: function (url, data, callback, async) {
        this.ajaxSubmit(url, data, callback, 'post', async)
    },
    /**
     * 不足10位补零
     * 参数：num
     */
    complement: function (num) {
        num = Number(num)
        return num < 10 ? '0' + num : num;
    },
    /**
     * 获取url中的参数
     * @param name
     * @returns {*}
     */
    getQueryString: function (name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        }
        return null;
    },
    /**
     * 查看图片
     * 参数：img
     */
    getLookImg: function (img) {
        var imgArr = [];
        $.each(img, function (i, item) {
            imgArr.push($(item).data('src'))
            $(item).unbind().bind('click', function () {
                showImg.open(i)
            })
        })
        var showImg = $.photoBrowser({
            items: imgArr,
            initIndex: 0
        })
    }
};



